import { app, shell, BrowserWindow, desktopCapturer, ipcMain, globalShortcut } from 'electron'
import * as path from 'path'
// import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import fs from "fs"

let mainWindow

function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        // titleBarStyle: 'hidden',
        width: 400,
        height: 500,
        titleBarStyle: 'hidden',
        maximizable: false,
        resizable: false,
        // eslint-disable-next-line no-dupe-keys
        // titleBarOverlay: {
        //   color: 'RGB(30,30,30)',
        //   symbolColor: '#74b1be'
        // },
        // 隐藏原生窗口菜单栏
        autoHideMenuBar: true,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })
    // mainWindow.webContents.openDevTools()
    mainWindow.on('ready-to-show', () => {
        mainWindow.show()
    })

    ipcMain.handle('get_media', async (win, n) => {
        let sources = await desktopCapturer.getSources({ types: ['window', 'screen'] })
        return sources
    })

    ipcMain.on('min_size', () => {
        mainWindow.minimize()
    })

    ipcMain.on('close_win', () => {
        app.quit()
    })


    // ipcMain.handle('get_stream', (win, sourceId) => {
    //   console.log('main', sourceId);
    //   mainWindow.webContents.send('SET_SOURCE', sourceId)
    // })
    // ipcMain.handle('save_video', (win, file) => {
    //   console.log('触发读写');
    //   fs.writeFileSync(path.join(process.cwd(), 'new.MP4'), file)
    // })


    mainWindow.webContents.setWindowOpenHandler((details) => {
        shell.openExternal(details.url)
        return { action: 'deny' }
    })

    // HMR for renderer base on electron-vite cli.
    // Load the remote URL for development or the local html file for production.
    if (process.env.ENV_NOW === 'development') {
        mainWindow.loadURL('http://localhost:' + process.env.WEB_PORT)
    } else {
        mainWindow.loadFile('index.html')
    }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    // Set app user model id for windows
    // electronApp.setAppUserModelId('com.electron')

    createWindow()

    const ret = globalShortcut.register('F6', () => {
        mainWindow.webContents.send('set_start')
    })

    const ref = globalShortcut.register('F7', () => {

        mainWindow.webContents.send('set_stop')
    })

    if (!ret || !ref) {
        console.log('registration failed')
    }


    // Default open or close DevTools by F12 in development
    // and ignore CommandOrControl + R in production.
    // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
    // app.on('browser-window-created', (_, window) => {
    //     optimizer.watchWindowShortcuts(window)
    // })



    app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('will-quit', () => {
    // 注销所有快捷键
    globalShortcut.unregisterAll()
})


// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
